const app = getApp()
var flag0 = false;



var flag = false;
var imageList = null;

var form_data;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    texts: "",

    tempFilePaths: [],
    title: "",
    talkText: "",
    
    picture: null,

    icontype: ["info_circle", "info"],
    word: "请不要发表不当言论！否则会被删帖！"

  },

  //点击提交
  formSubmit: function (e) {
    var warn = "";//弹框时提示的内容
    var flag = true;//判断信息输入是否完整
    
    if (e.detail.value.title == "") {
      warn = "请输入标题";
    } else if (e.detail.value.talkText == "") {
      warn = "请选择发表内容";
    } else {

      flag = false;//若必要信息都填写，则不用弹框，且页面可以进行跳转
      var that = this;

      ///////////////////操作数据库，     
      console.log('imageList：', imageList);
      /////////////////////////////////////////////上传图片
      if (imageList == null) {//当上传图片为0时，只提交表单的文字信息
        wx.request({
          url: app.globalData.baseUrl + '/talk/insertTalk',
          data: {//获取数据传到后台
            buyerOpenid: wx.getStorageSync("openid"),
            talkText: e.detail.value.talkText,
            title: e.detail.value.title,
            picture: null
          },
          method: "POST",
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            var result = res.data.success
            console.log('result：', res.data.success);
            console.log('talkText：', e.detail.value.talkText);
            console.log('title：', e.detail.value.title);
            
            var toastText = "操作成功！";
            if (result == false) {
              toastText = "信息不全";
            }
            if (result != "fail") {
              wx.showToast({
                title: toastText,
                icon: '',
                duration: 2000
              });
            }

            if (result == true) {
              wx.redirectTo({
                url: '../homepage/homepage'

              })
            }
            var flag1 = false;
            if (result == "fail") {
              flag1 = true;
              
            }
            

            if (flag1 == true) {
              wx.showModal({
                title: '提示',
                content: warn
              })
            }


          }
        })
      } else {
        console.log("upload图片列表", imageList.length);
        var that = this;
        var images_list = []; //设置了一个空数组进行储存服务器端图片路径
        for (var i = 0; i < imageList.length; i++) {
          wx.uploadFile({
            url: app.globalData.baseUrl + '/order/upload',
            filePath: imageList[i],
            name: 'file',
            formData: null,
            success: function (res) {
              console.log(res.data)
              //console.log(res.data)
              //后端返回图片上传到服务器上边的地址的json
              //图片json转换数组
              var jsonObj = JSON.parse(res.data)
              console.log(jsonObj.url)
              images_list.push(jsonObj.url);
              if (imageList.length == images_list.length) {//只有当图片全部上传成功才能提交表单，因为表单只需要提交一次
                var images_str = images_list.join(",")//把存放图片地址的数组转化为以逗号分隔的字符串
                console.log("images_str:", images_str)
                wx.request({
                  url: app.globalData.baseUrl + '/talk/insertTalk',
                  data: {//获取数据传到后台
                    buyerOpenid: wx.getStorageSync("openid"),
                    talkText: e.detail.value.talkText,
                    title: e.detail.value.title,
                    picture: images_str
                  },
                  method: "POST",
                  header: {
                    "Content-Type": "application/x-www-form-urlencoded" // 默认值
                  },
                  success(res) {//success只能说明接口调取并返回成功，并不是代表信息上传成功，还需要判断返回的信息
                    var result = res.data.success
                    console.log('result：', res.data.success);
                    console.log('talkText：', e.detail.value.talkText);
                    console.log('title：', e.detail.value.title);
                    var toastText = "操作成功！";
                    if (result != true) {
                      toastText = "信息不全" + res.data.errMsg;
                    }
                    wx.showToast({
                      title: toastText,
                      icon: '',
                      duration: 2000
                    });
                    if (result == true) {
                      wx.redirectTo({
                        url: '../homepage/homepage'

                      })
                    }

                    imageList = null;

                  }
                })
              }

            },
            fail: function (error) { }
          })
        }

      }








    }
    //如果信息填写不完整，弹出输入框
    if (flag == true) {
      wx.showModal({
        title: '提示',
        content: warn
      })



    }


  },

  getImageList(e) {
    let that = this;
    console.log("获取上传图片");
    //console.log(e.detail);
    imageList = e.detail;
    console.log("图片列表", imageList);

  },

  ///////////上传图片
  upload: function () {
    console.log("upload图片列表", imageList.length);
    var that = this;
    var images_list = []; //设置了一个空数组进行储存服务器端图片路径
    for (var i = 0; i < imageList.length; i++) {
      wx.uploadFile({
        url: app.globalData.baseUrl + '/order/upload',
        filePath: imageList[i],
        name: 'file',
        formData: null,
        success: function (res) {
          console.log(res.data)
          //console.log(res.data)
          //后端返回图片上传到服务器上边的地址的json
          //图片json转换数组
          var jsonObj = JSON.parse(res.data)
          console.log(jsonObj.url)
          images_list.push(jsonObj.url);
          if (imageList.length == images_list.length) {//只有当图片全部上传成功才能提交表单，因为表单只需要提交一次
            var images_str = images_list.join(",")//把存放图片地址的数组转化为以逗号分隔的字符串
            console.log(images_str)
            wx.request({
              url: app.globalData.baseUrl + '/order/orderinsert',
              method: 'POST',
              data: {
                serviceTime: that.data.yyTime,
                addressId: that.data.addressId,
                //orderAmount: that.data.recommendedPrice,
                orderAmount: amount,
                orderRemark: e.detail.value.orderRemark,
                category2Id: wx.getStorageSync("category2ToOrder"),
                imageList: images_str
              },
              header: {
                "Content-Type": "application/x-www-form-urlencoded" // 默认值
              },
              success(res) {//success只能说明接口调取并返回成功，并不是代表信息上传成功，还需要判断返回的信息
                var result = res.data.success
                console.log('result：', res.data.success);
                console.log('serviceTime：', that.data.yyTime);
                console.log('addressId：', that.data.addressId);
                console.log('orderAmount：', e.detail.value.recommendedPrice);
                console.log('orderRemark：', that.data.orderRemark);
                var toastText = "操作成功！";
                if (result != true) {
                  toastText = "信息不全" + res.data.errMsg;
                }
                wx.showToast({
                  title: toastText,
                  icon: '',
                  duration: 2000
                });
                if (result == true) {
                  wx.redirectTo({
                    url: '../order/confirm/index'

                  })


                }

              }
            })
          }
          
        },
        fail: function (error) { }
      })
    }
   
  },


  onShow: function (e) {
    var that = this;
    wx.request({
      url: app.globalData.baseUrl + '/worker/getworker',
      method: 'GET',
      data: { "openId": wx.getStorageSync('openid') },//传入的参数
      success: function (res) {
        var worker = res.data.worker;
        console.log("worker0:", worker)
        var userInfo = wx.getStorageSync('userInfo');
        that.setData({ userInfo: userInfo });

        if (worker == "null") {
          console.log("进来这里")
          
        } else {
          var picture = [];
          picture.push(app.globalData.baseUrl + worker.picture);
          that.setData({
            name: worker.name,
            phone: worker.phone,
            score: worker.score,
            //tempFilePaths: picture
          });
        }
      }
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.request({
      url: app.globalData.baseUrl + '/worker/getworker',
      method: 'GET',
      data: { "openId": wx.getStorageSync('openid') },//传入的参数
      success: function (res) {
        var worker = res.data.worker;
        console.log("worker0:", worker)
        var userInfo = wx.getStorageSync('userInfo');
        that.setData({ userInfo: userInfo });

        if (worker == "null") {
          console.log("进来这里")
          
        } else {
          var picture = [];
          picture.push(app.globalData.baseUrl + worker.picture);
          that.setData({
            name: worker.name,
            phone: worker.phone,
            score: worker.score,
            tempFilePaths: picture
          });
        }
      }
    })
  },
  exit: function (e) {
    wx.showModal({
      title: '提示',
      content: '是否确认退出',
      success: function (res) {
        if (res.confirm) {
          // console.log('用户点击确定')
          wx.removeStorageSync('userInfo');
          //页面跳转
          wx.redirectTo({
            url: '../user/user',
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  /**
   * 上传图片方法
   */
  upload: function () {
    let that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: res => {
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 1000
        })
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        let tempFilePaths = res.tempFilePaths;

        that.setData({
          tempFilePaths: tempFilePaths
        })
        flag0 = true;
        /**
         * 上传完成后把文件上传到服务器
         */
        var count = 0;
        for (var i = 0, h = tempFilePaths.length; i < h; i++) {
          
        }

      }
    })
  },
  /**
   * 预览图片方法
   */
  listenerButtonPreviewImage: function (e) {
    let index = e.target.dataset.index;
    let that = this;
    console.log(that.data.tempFilePaths[index]);
    console.log(that.data.tempFilePaths);
    wx.previewImage({
      current: that.data.tempFilePaths[index],
      urls: that.data.tempFilePaths,
      //这根本就不走
      success: function (res) {
        //console.log(res);
      },
      //也根本不走
      fail: function () {
        //console.log('fail')
      }
    })
  },
  /**
   * 长按删除图片
   */
  deleteImage: function (e) {
    var that = this;
    var tempFilePaths = that.data.tempFilePaths;
    var index = e.currentTarget.dataset.index;//获取当前长按图片下标
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          console.log('点击确定了');
          tempFilePaths.splice(index, 1);
        } else if (res.cancel) {
          console.log('点击取消了');
          return false;
        }
        that.setData({
          tempFilePaths
        });
      }
    })
  }
})
